package com.zlsy.thread.atomic;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author zhouliang
 * @date 2020/8/12 17:03
 * 演示AtomicIntegerFieldUpdater的用法
 */
public class AtomicIntegerFieldUpdaterDemo implements Runnable {

    public static AtomicIntegerFieldUpdater<Candidate> atomicIntegerFieldUpdater = AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
    static Candidate tom;
    static Candidate petter;

    public static void main(String[] args) throws InterruptedException {
        AtomicIntegerFieldUpdaterDemo r = new AtomicIntegerFieldUpdaterDemo();
        tom = new Candidate();
        petter = new Candidate();

        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(String.format("普通变量:%s", petter.score));
        System.out.println(String.format("atomicIntegerFieldUpdater变量：%s", tom.score));
    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            petter.score++;
            atomicIntegerFieldUpdater.getAndIncrement(tom);
        }
    }

    public static class Candidate {
        volatile int score;
    }
}
